<template>
  <div>
    <!-- 控制侧边栏图标 -->
    <Icon
      v-show="show_con_ico"
      @click="collapsedSider"
      type="ios-settings-outline"
      size="24"
      style="
        z-index: 3;
        float: right;
        position: fixed;
        overflow: auto;
        right: 60px;
        top: 18px;
      "
    ></Icon>

    <!-- 控制目录图标 -->

    <Icon
      v-show="show_catalog_ico"
      @click="clik_showcatalog"
      type="ios-bookmark-outline"
      size="24"
      style="
        z-index: 3;
        float: right;
        position: fixed;
        overflow: auto;
        right: 18px;
        top: 18px;
      "
    ></Icon>

    <!-- 侧边栏 -->
    <Sider
      :width="250"
      collapsible
      hide-trigger
      :collapsed-width="0"
      v-model="isCollapsed"
      :style="{
        position: 'fixed',
        height: '100vh',
        left: 0,
        top: '55px',
        overflow: 'auto'
      }"
      style="
        z-index: 1;
        background-color: #fff;
        border-right-width: 2px;
        border-color: rgb(220, 222, 226);
        border-style: solid;
      "
    >
      <!-- <h3 style="text-align: center">所有文章</h3> -->
      <!-- 搜索框 -->
      <Input
        v-model="search_info"
        search
        enter-button
        placeholder="搜索文章..."
        @on-search="click_search"
        style="padding: 10px; padding-top: 20px"
      />
      <!-- 目录树 -->
      <Tree
        style="padding: 10px"
        expand-node
        :data="tree_data"
        class="demo-tree-render"
        @on-toggle-expand="get_showList"
      ></Tree>
    </Sider>

    <!-- 本文目录 -->
    <Sider
      :width="220"
      collapsible
      hide-trigger
      :collapsed-width="0"
      v-model="Collapsed_catalog"
      :style="{
        position: 'fixed',
        height: '100vh',
        right: 0,
        top: '0px',
        overflow: 'auto',
        padding: sider_padding
      }"
      style="
        padding-top: 55px;
        z-index: 1;
        background-color: #fff;
        border-right-width: 1px;
        border-color: rgb(220, 222, 226);
        border-style: solid;
        
      "
    >
      <div>
        <div style="text-align: center">
          <h4 style="text-align: center">本文目录</h4>
          <Icon
            title="切换显示模式"
            :size="24"
            type="ios-analytics-outline"
            @click="cata_show_model = cata_show_model == 'pre' ? '' : 'pre'"
          />
        </div>
        <p
          :title="item.text"
          :style="'white-space: ' + cata_show_model + ';'"
          v-for="(item, i) in show_title_list"
          :key="i"
          :class="item.type"
          @click="roll_to_title(item.id, $event)"
        >
          {{ item.text }}
        </p>
      </div>
    </Sider>

    <div
      @click="click_content"
      style="height: 100vh"
      :style="
        'padding-left:' + padding_left + ';padding-right:' + padding_right
      "
    >
      <!-- 编辑器 -->
      <div v-show="Display_Editor">
        <Editor @trans_editor="get_editor"></Editor>
      </div>
      <!-- pdf -->
      <iframe
        :style="{
          width: '-webkit-fill-available',
          height: '100vh'
        }"
        v-show="Display_pdf"
        :src="show_pdfFile_path"
      ></iframe>
      <!-- 展示列表 -->
      <List v-show="Display_list" item-layout="vertical">
        <ListItem
          v-for="(item, i) in showDadaList"
          :key="i"
          style="margin: 20px 10px"
        >
          <ListItemMeta
            :avatar="head_photo"
            :title="item.title"
            :description="item.upload.explain"
            @click="show_artice_doc(item)"
          />
          <!-- {{ item.upload.explain }} -->
          <template #action>
            <li>
              <Icon type="ios-time-outline" />发布:
              {{ item.upload.release_time }}
            </li>

            <li>
              <Icon type="ios-clock-outline" /> 更新:{{
                item.upload.update_time
              }}
            </li>
            <li v-if="item.upload.permission == '仅自己'">
              <span>查看:</span
              ><span style="color: red">{{ item.upload.permission }}</span>
            </li>
            <li>
              <Icon type="ios-star-outline" />
            </li>
            <li>
              <Icon type="ios-thumbs-up-outline" />
            </li>
            <li>
              <Icon type="ios-chatbubbles-outline" />
            </li>
          </template>
        </ListItem>
      </List>
    </div>
  </div>
</template>

<script>
import {
  aliyun_oss_path,
  nodeType_children_node,
  nodeType_root_node,
  nodeType_pdf,
  nodeType_article,
  pdfjs_path,
  break_width,
  editor_h1,
  editor_h2,
  editor_h3,
  editor_h4,
  editor_h5,
  PATH_homepage_headphoto
} from '@/mylibs/define'
import get_oss_data from '@/api/aliyun_oss'
import { resolveComponent } from 'vue'
import Editor from '@/components/Editor/Editor.vue'
import eventBus from '@/eventBus/eventBus'
import { is_signin } from '@/api/API_sign_in_out'
export default {
  name: 'Programming_content',
  components: { Editor },
  props: ['PATH_Directory_tree'],
  data() {
    return {
      cata_show_model: '',
      no_hits_num: 0,
      search_info: '',
      head_photo: null,
      tree_data: [],
      isCollapsed: false,
      edtior: null,
      // 右侧链接展示区的数据
      showDadaList: [],
      Display_Editor: false,
      Collapsed_catalog: true,
      Display_pdf: false,
      Display_list: true,
      show_pdfFile_path: '',
      pdfjs_path,
      // 文章目录,获取本文标题h12345 列表
      show_title_list: [],
      padding_left: '250px',
      padding_right: '200px',
      screenWidth: null,
      screenHeight: 700,
      show_con_ico: true,
      sider_padding: '0px',
      show_catalog_ico: false,
      buttonProps: {
        type: 'default',
        size: 'small'
      }
    }
  },

  watch: {
    screenWidth(newvar) {
      // 小屏幕
      if (newvar < break_width) {
        this.isCollapsed = true
        this.padding_left = '0px'
        this.show_catalog_ico = true
        this.Collapsed_catalog = true
        this.padding_right = '5px'
      } else {
        this.isCollapsed = false
        this.padding_left = '250px'
        this.show_catalog_ico = false

        if (this.Display_Editor) {
          this.Collapsed_catalog = false
          this.padding_right = '200px'
        }

        if (this.Display_pdf) {
          this.padding_right = '0px'
        }
      }
    },

    Collapsed_catalog(newvar) {
      if (!newvar) {
        this.sider_padding = '5px'
      } else {
        this.sider_padding = '0px'
      }
    },

    Display_Editor(newvar) {
      if (this.screenWidth >= break_width) {
        this.Collapsed_catalog = !newvar
      }
    }
  },

  methods: {
    //递归目录树数据,设置不同样式
    Recursive_directory_tree(dirData) {
      for (let index = 0; index < dirData.length; index++) {
        const element = dirData[index]
        // 设置根文章节点样式
        if (element.node_type && element.node_type == nodeType_article) {
          element['render'] = (h, { root, node, data }) => {
            return h(
              'span',
              {
                style: {
                  display: 'inline-block',
                  width: '100%'
                }
              },
              [
                h('span', [
                  h(resolveComponent('Icon'), {
                    type: 'ios-paper-outline',
                    style: {
                      marginRight: '8px'
                    }
                  }),
                  h('span', data.title)
                ]),
                h(
                  'span',
                  {
                    style: {
                      display: 'inline-block',
                      float: 'right',
                      marginRight: '10px'
                    }
                  },
                  [
                    h(resolveComponent('Button'), {
                      ...this.buttonProps,
                      icon: 'ios-paper-plane-outline',
                      style: {},
                      onClick: () => {
                        this.show_artice_doc(data)
                      }
                    })
                  ]
                )
              ]
            )
          }
        }
        // pdf
        if (element.node_type && element.node_type == nodeType_pdf) {
          element['render'] = (h, { root, node, data }) => {
            return h(
              'span',
              {
                style: {
                  display: 'inline-block',
                  width: '100%'
                }
              },
              [
                h('span', [
                  h(resolveComponent('Icon'), {
                    type: 'ios-leaf-outline',
                    style: {
                      marginRight: '8px'
                    }
                  }),
                  h('span', data.title)
                ]),
                h(
                  'span',
                  {
                    style: {
                      display: 'inline-block',
                      float: 'right',
                      marginRight: '10px'
                    }
                  },
                  [
                    h(resolveComponent('Button'), {
                      ...this.buttonProps,
                      icon: 'ios-paper-plane-outline',
                      style: {},
                      onClick: () => {
                        this.show_artice_doc(data)
                      }
                    })
                  ]
                )
              ]
            )
          }
        }
        // 子文件夹样式
        if (element.node_type && element.node_type == nodeType_children_node) {
          element['render'] = (h, { root, node, data }) => {
            return h(
              'span',
              {
                style: {
                  display: 'inline-block',
                  width: '100%'
                }
              },
              [
                h('span', [
                  h(resolveComponent('Icon'), {
                    type: 'ios-folder-open-outline',
                    style: {
                      marginRight: '8px'
                    }
                  }),
                  h('span', data.title)
                ])
              ]
            )
          }
        }
        // 根文件夹样式
        if (element.node_type && element.node_type == nodeType_root_node) {
          element['render'] = (h, { root, node, data }) => {
            return h(
              'span',
              {
                style: {
                  display: 'inline-block',
                  width: '100%'
                }
              },
              [
                h('span', [
                  // vue3
                  h(resolveComponent('Icon'), {
                    type: 'ios-folder-outline',
                    style: {
                      marginRight: '8px'
                    }
                  }),
                  h('span', data.title)
                ])
              ]
            )
          }
        }
        if (element.children && element.children.length != 0) {
          // 子文件夹
          this.Recursive_directory_tree(element.children)
        }
      }
    },

    // 从oss获取目录树数据
    async getTreeData(fun_back) {
      var { res, ok, err } = await get_oss_data(
        aliyun_oss_path + this.PATH_Directory_tree
      )
      if (ok) {
        if (Array.isArray(res)) {
          this.tree_data = res
          this.Recursive_directory_tree(this.tree_data)
          if (fun_back) {
            fun_back(this.tree_data[0])
          }
        } else {
          this.$Notice.error({ desc: '数据非数组' })
        }
      } else {
        this.$Notice.error({ desc: '获取数据失败' })
      }
    },

    // 获取编辑器
    get_editor(editor) {
      this.edtior = editor
    },

    // 获取展示区数据
    get_showList(node, isRec) {
      if (!node || !node.children) return

      // 不显示编辑器
      this.Display_Editor = false
      this.Display_pdf = false
      this.Display_list = true

      if (!isRec) {
        this.showDadaList.splice(0, this.showDadaList.length)
      }
      for (let index = 0; index < node.children.length; index++) {
        const element = node.children[index]

        if (element.node_type && element.node_type == nodeType_article) {
          this.showDadaList.push(element)
        }

        if (element.node_type && element.node_type == nodeType_pdf) {
          this.showDadaList.push(element)
        }

        // 递归子文件夹
        if (element.children && element.children.length != 0) {
          this.get_showList(element, true)
        }
      }
    },

    // 具体显示文章,文档
    async show_artice_doc(node) {
      //   文章
      if (node.node_type == nodeType_article) {
        // 仅自己可见
        if (node.upload.permission == '仅自己') {
          if (this.no_hits_num > 20) {
            this.$Notice.info({
              desc: '抱歉,您暂时没有权限查看次篇文章哟~~~'
            })
            return
          }
          // 判断是否登录
          is_signin(async ({ data }) => {
            if (data.ret == 0) {
              try {
                var { res, ok, err } = await get_oss_data(
                  aliyun_oss_path + node.upload.bucket_filepath
                )
                if (ok) {
                  this.edtior.setHtml(res.editor_data)
                  // 显示编辑器
                  this.Display_Editor = true
                  this.Display_list = false
                  this.Display_pdf = false
                  if (this.screenWidth >= break_width) {
                    this.padding_right = '200px'
                  }
                  // 获取目录
                } else {
                  this.$Notice.error({
                    desc: '获取文章的编辑器数据失败:' + err
                  })
                }
              } catch (e) {
                this.$Notice.error({ desc: '对象可能没有该属性:' + e })
                console.log(e)
              }
            } else {
              this.no_hits_num++
              this.$Notice.info({
                desc: '抱歉,您暂时没有权限查看次篇文章哟~~~'
              })
            }
          })
        } else {
          // 全部可见
          try {
            var { res, ok, err } = await get_oss_data(
              aliyun_oss_path + node.upload.bucket_filepath
            )
            if (ok) {
              this.edtior.setHtml(res.editor_data)
              // 显示编辑器
              this.Display_Editor = true
              this.Display_pdf = false
              this.Display_list = false
              if (this.screenWidth >= break_width) {
                this.padding_right = '200px'
              }
              // 获取目录
            } else {
              this.$Notice.error({ desc: '获取文章的编辑器数据失败:' + err })
            }
          } catch (e) {
            this.$Notice.error({ desc: '对象可能没有该属性:' + e })
            console.log(e)
          }
        }
      }
      //   pdf
      if (node.node_type == nodeType_pdf) {
        if (node.upload.permission == '仅自己') {
          is_signin(async ({ data }) => {
            if (data.ret == 0) {
              var url =
                aliyun_oss_path +
                encodeURIComponent(node.upload.bucket_filepath)

              this.show_pdfFile_path = this.pdfjs_path + url
              // 显示pdfjs,不显示预览列表
              this.Display_pdf = true
              this.Display_list = false
              this.Display_Editor = false
              this.padding_right = '5px'
            } else {
              this.$Notice.info({
                desc: '抱歉,您暂时没有权限查看次篇文章哟~~~'
              })
            }
          })
        } else {
          var url =
            aliyun_oss_path + encodeURIComponent(node.upload.bucket_filepath)

          this.show_pdfFile_path = this.pdfjs_path + url
          // 显示pdfjs,不显示预览列表
          this.Display_pdf = true
          this.Display_list = false
          this.Display_Editor = false
          this.padding_right = '5px'
        }
      }
    },

    // 搜索文章
    search_data(list) {
      var datalist = this.tree_data
      if (list) {
        datalist = list
      } else {
        this.showDadaList.splice(0, this.showDadaList.length)

        // 不显示编辑器
        this.Display_Editor = false
        this.Display_pdf = false
        this.Display_list = true
      }

      for (let index = 0; index < datalist.length; index++) {
        var element = datalist[index]
        if (
          element.title.indexOf(this.search_info) != -1 &&
          (element.node_type == nodeType_article ||
            element.node_type == nodeType_pdf)
        ) {
          this.showDadaList.push(element)
        }

        // 递归子文件夹
        if (element.children && element.children.length != 0) {
          this.search_data(element.children)
        }
      }
    },

    click_search() {
      this.search_data()
    },

    // 跳转到标题
    roll_to_title(id, e) {
      if (e) {
        e.stopPropagation()
      }
      this.edtior.scrollToElem(id)
    },

    // 点击了侧边栏控制图标
    collapsedSider(e) {
      e.stopPropagation()
      this.isCollapsed = !this.isCollapsed
      if (this.screenWidth >= break_width && this.isCollapsed) {
        this.padding_left = '10px'
      } else if (this.screenWidth >= break_width && !this.isCollapsed) {
        this.padding_left = '250px'
      }
    },

    // 点击控制目录图标
    clik_showcatalog(e) {
      e.stopPropagation()
      if (this.Display_Editor) {
        this.Collapsed_catalog = !this.Collapsed_catalog
      }
    },

    get_headphoto() {
      get_oss_data(aliyun_oss_path + PATH_homepage_headphoto).then(
        ({ res, ok, err }) => {
          if (ok) {
            if (res.img) {
              this.head_photo = res.img
            }
          }
        }
      )
    },
    click_content() {
      if (this.screenWidth < break_width) {
        this.isCollapsed = true
        this.Collapsed_catalog = true
      }
    }
  },

  // 生命周期
  created() {
    this.get_headphoto()
    this.getTreeData(this.get_showList),
      // 文章目录,获取本文标题h12345
      eventBus.on('get_show_title_list', (list) => {
        if (Array.isArray(list)) {
          // 对标题进行处理
          for (let index = 0; index < list.length; index++) {
            var element = list[index]

            if (element.type == editor_h2) {
              element.text = '' + element.text
            } else if (element.type == editor_h3) {
              element.text = '' + element.text
            } else if (element.type == editor_h4) {
              element.text = '' + element.text
            } else if (element.type == editor_h5) {
              element.text = '' + element.text
            }
          }

          this.show_title_list = list
        } else {
          this.$Notice.error({ desc: '文章标题数据非数组' })
        }
      })

    //屏幕变化
    eventBus.on('ev_screen_width_height', ({ w, h }) => {
      this.screenWidth = w
    })
    // // 点击了全屏
    // eventBus.on('home_content_clik', () => {
    //   if (this.screenWidth < break_width) {
    //     this.isCollapsed = true
    //     this.Collapsed_catalog = true
    //   }
    // })
  },

  activated() {
    //屏幕变化
    eventBus.on('ev_screen_width_height', ({ w, h }) => {
      this.screenWidth = w
      // iframe 的样式使用这个高度有bug,会无限增加
      // this.screenHeight = h
    })
  },

  mounted() {
    this.screenHeight = document.body.clientHeight
    window.onresize = () => {
      //屏幕尺寸变化就重新赋值
      return (() => {
        this.screenHeight = document.body.clientHeight
      })()
    }
  }
}
</script>

<style lang="less" scoped>
.demo-tree-render .ivu-tree-title {
  width: 100%;
}

.header1 {
  font-weight: 600;
  margin-left: 10px;
}

.header2 {
  font-weight: 500;
  margin-left: 30px;
}

.header3 {
  font-weight: 400;
  margin-left: 50px;
}

.header4 {
  font-weight: 300;
  margin-left: 70px;
}

.header5 {
  font-weight: 200;
  margin-left: 90px;
}
</style>
